// pages/auth/index.js
import { getOnceGlobalData } from '@/utils/util'
import { createSubmit, formInputChange } from '@/utils/form'
import { setToken, setHardID } from '@/utils/storage'
import { corpLogin } from '@/request/api/index'
import { onShareDefault } from '@/utils/share'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isPwdShow: false,

    formData: {
      userName: '',
      password: ''
    },
    rules: {
      userName: [{ required: true, message: '请输入用户名' }],
      password: [{ required: true, message: '请输入密码' }],
    }
  },

  customData: {
    tabPageKey: [
      'pages/overview/',
      'pages/action/',
      'pages/safe/',
      'pages/terminal/',
    ]
  },

  setPwdShow() {
    this.setData({
      isPwdShow: !this.data.isPwdShow
    })
  },

  /**
   * 登录后跳转对于页面
   */
  jumpPage () {
    const loginAfterUrl = getOnceGlobalData('loginAfterUrl', '')
    const { tabPageKey = [] } = this.customData

    if (!loginAfterUrl) {
      wx.switchTab({ url: '/pages/index/index' })
    } else if (tabPageKey.some(key => loginAfterUrl.indexOf(key) !== -1)) {
      wx.switchTab({ url: `/${loginAfterUrl}` })
    } else {
      wx.redirectTo({ url: `/${loginAfterUrl}` })
    }
  },

  formInputChange,

  submitForm: createSubmit(async function() {
    const { userName, password } = this.data.formData
    
    const { Data = {}, Token } = await corpLogin({
      UserID: userName,
      Password: password
    })
    
    setToken(Token)
    setHardID(Data.HardID)

    this.jumpPage()
  }, {
    msg: '登录成功',
    ruleSource: 'rules',
    formSource: 'formData',
    isErrToast: true
  }),

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: onShareDefault()
})